package com.infolab.aims.common;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CommonUtil {

	public static String getStackTrace(Throwable e) {
		if (e == null) {
			return "";
		}

		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			PrintWriter pw = new PrintWriter(bos);
			e.printStackTrace(pw);
			pw.flush();

			String stackTrace = bos.toString();
			// conserve memory
			bos = null;
			pw = null;

			return stackTrace;
		} catch (Exception e1) {
			// should not happen
			// log this, and return "" instead
			return "";
		}
	}

	public static Date toDate(String value, String format) {
		try {
			DateFormat formatter = new SimpleDateFormat(format);
			return formatter.parse(value);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date pickMonth(Date date, int month) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, -1);
		return c.getTime();

	}
}
